package com.fly.files;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import lombok.extern.slf4j.Slf4j;

/**
 * 随机选择文件，向后写入文件内容
 */
@Slf4j
public class FileExchange
{
    static String path = System.getenv().get("USERPROFILE") + "\\Pictures\\";
    
    File directory = new File(path);
    
    /**
     * 创建测试文件
     */
    @BeforeAll
    public static void init()
    {
        IntStream.rangeClosed(0, 10).forEach(i -> {
            try
            {
                File file = new File(path + i + ".txt");
                FileUtils.writeStringToFile(file, Objects.toString(i), StandardCharsets.UTF_8);
            }
            catch (IOException e)
            {
                log.error(e.getMessage(), e);
            }
        });
    }
    
    @Test
    public void test()
        throws IOException
    {
        List<File> files = FileUtils.listFiles(directory, new String[] {"txt"}, true).stream().collect(Collectors.toList());
        
        // 随机选择多个
        List<File> chooseFiles = new Random().ints(5, 0, files.size())
            .mapToObj(index -> files.get(index))
            .distinct()// 去重后打印
            .peek(f -> log.info("{}", f.getAbsolutePath()))
            .collect(Collectors.toList());
        
        int length = chooseFiles.size();
        if (length > 1)
        {
            // 读取文件内容
            List<String> texts = chooseFiles.stream().map(file -> readText(file)).collect(Collectors.toList());
            if (texts.stream().allMatch(StringUtils::isNotBlank))
            {
                AtomicInteger index = new AtomicInteger();
                texts.forEach(text -> {
                    try
                    {
                        // 依次写入后面临近文件
                        File dest = chooseFiles.get(index.incrementAndGet() % length);
                        FileUtils.writeStringToFile(dest, text, StandardCharsets.UTF_8);
                        log.info("{} ===> {}", text, dest.getAbsolutePath());
                    }
                    catch (IOException e)
                    {
                        log.error(e.getMessage(), e);
                    }
                });
            }
        }
        if (SystemUtils.IS_OS_WINDOWS)
        {
            String openCmd = RandomUtils.nextBoolean() ? "explorer " : "cmd /c start ";
            Runtime.getRuntime().exec(openCmd + path);
        }
    }
    
    /**
     * 读取文件文本内容
     * 
     * @param file
     * @return
     */
    private String readText(File file)
    {
        try
        {
            return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
